from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from user03.models import User
from hashlib import md5, sha1, sha256
import json
from django.views import View
from django.utils.decorators import method_decorator


# Create your views here.
def register(request):
    new_md5 = md5()
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        req_dict = json.loads(request.body)
        username = req_dict.get('username')
        password = req_dict.get('password')
        # username = request.POST['username']
        # password = request.POST['password']
        new_md5.update(password.encode('utf-8'))
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = User.objects.create(username=username, password=new_md5.hexdigest())
            return redirect('/login/')
        else:
            return JsonResponse({'massage': 'register failed'})
        # return JsonResponse({'key':'注册成功'})


class Register(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        new_md5 = md5()
        # req_dict = json.loads(request.body)
        # username = req_dict.get('username')
        # password = req_dict.get('password')
        username = request.POST['username']
        password = request.POST['password']
        new_md5.update(password.encode('utf-8'))
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = User.objects.create(username=username, password=new_md5.hexdigest())
            return redirect('/login/')
        else:
            return JsonResponse({'massage': 'register failed'})


def session(fn):
    def inner(request):
        username = request.session.get('username')
        if username:
            return HttpResponse('%slogin successed' % username)
        return fn(request)

    return inner


class LoginView(View):

    @method_decorator(session)
    def get(self, request):
        # username = request.session.get('username')
        # if username:
        #     return HttpResponse('%slogin successed' % username)
        username = request.COOKIES.get('username', '')
        if username == '':
            return render(request, 'login.html')
        else:
            return render(request, 'login.html', context={'name': username})

    @method_decorator(session)
    def post(self, request):
        new_md5 = md5()
        # username = request.session.get('username')
        # if username:
        #     return HttpResponse('%slogin successed' % username)
        username = request.POST.get('username')
        password = request.POST.get('password')
        new_md5.update(password.encode('utf-8'))
        remember = request.POST.get('remember')
        try:
            user = User.objects.get(username=username, password=new_md5.hexdigest())
        except User.DoesNotExist:
            return JsonResponse({'massage': 'login failed'})
        else:
            response = JsonResponse({'massage': 'login successed'})
            response.set_cookie('username', username, max_age=14 * 24 * 3600)
            request.session['user_id'] = user.id
            request.session['username'] = user.username
            if not remember:
                request.session.set_expiry(0)
            return response


def user_info(request, ide):
    print(request)
    try:
        user = User.objects.get(id=ide)
    except User.DoesNotExist:
        return JsonResponse({'message': 'shibai'})
    else:
        return JsonResponse({
            'id': user.id,
            'name': user.username,
            'gender': user.gender,
            'mobile': user.mobile
        })
